package com.niit.cms.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 实现用户登录拦截
 * @Author: cao_jiaqi
 * @CreateTime： 2022/6/22 9:47
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{
    /**
     * @Description: 在调用控制器之前触发
     * 返回false,相当于拦截请求，不再继续执行
     * 返回true,通过拦截，放行
     * @Author: cao_jiaqi
     * @CreateTime: 2022/6/22 10:08
     * @param: request
     * @param: response
     * @param: handler
     * @return: boolean
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入到了登录拦截器LoginInterceptor - preHandle");
        //1.获取用户请求URL
        String URI = request.getRequestURI();
        String URL = request.getRequestURL().toString();
        System.out.println("进入到了登录拦截器LoginInterceptor - preHandle URI = " + URI + " URL = " + URL);
        Object userObj = request.getSession().getAttribute("user");
        if(userObj == null){
            System.out.println("进入到了登录拦截器LoginInterceptor - preHandle 将【" + URI + "】 拦截，拦截原因：未登录 ");
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入到了登录拦截器LoginInterceptor - postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入到了登录拦截器LoginInterceptor - afterCompletion");
    }
}
